const { favoriteAPI } = require('../../../utils/api.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    favoriteList: [], // 收藏列表
    pageNum: 1, // 当前页码
    pageSize: 10, // 每页数量
    hasMore: true, // 是否还有更多数据
    loading: false, // 加载状态
    isLoggedIn: false // 登录状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLoginStatus();
    if (this.data.isLoggedIn) {
      this.loadFavoriteList(true);
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (userInfo && token) {
      this.setData({
        isLoggedIn: true
      });
    } else {
      this.setData({
        isLoggedIn: false
      });
    }
  },

  /**
   * 跳转到登录页面
   */
  goToLogin() {
    wx.switchTab({
      url: '/pages/my/mycenter/mycenter'
    });
  },

  /**
   * 跳转到律师团队页面
   */
  goToTeam() {
    wx.switchTab({
      url: '/pages/team/team'
    });
  },

  /**
   * 加载收藏列表
   */
  async loadFavoriteList(refresh = false) {
    if (this.data.loading) return;

    const { pageNum, pageSize } = this.data;
    
    if (refresh) {
      this.setData({
        pageNum: 1,
        hasMore: true,
        favoriteList: []
      });
    }

    if (!this.data.hasMore) return;

    this.setData({ loading: true });

    try {
      const res = await favoriteAPI.list(refresh ? 1 : pageNum, pageSize);
      const newList = res.data.list || [];
      const total = res.data.total || 0;
      
      this.setData({
        favoriteList: refresh ? newList : [...this.data.favoriteList, ...newList],
        pageNum: refresh ? 2 : pageNum + 1,
        hasMore: (refresh ? newList.length : this.data.favoriteList.length + newList.length) < total
      });
    } catch (error) {
      wx.showToast({
        title: error.message || '获取收藏列表失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 取消收藏
   */
  cancelFavorite(e) {
    const lawyerId = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;

    wx.showModal({
      title: '提示',
      content: '确定要取消收藏吗？',
      success: (res) => {
        if (res.confirm) {
          this.cancelFavoriteToServer(lawyerId, index);
        }
      }
    });
  },

  /**
   * 调用取消收藏API
   */
  async cancelFavoriteToServer(lawyerId, index) {
    try {
      await favoriteAPI.cancel(lawyerId);
      
      // 从列表中移除
      const favoriteList = [...this.data.favoriteList];
      favoriteList.splice(index, 1);
      this.setData({
        favoriteList: favoriteList
      });
      
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      });
    } catch (error) {
      wx.showToast({
        title: error.message || '取消收藏失败',
        icon: 'none'
      });
    }
  },

  /**
   * 跳转到律师详情页
   */
  goToLawyerDetail(e) {
    const lawyerId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/team/teamDetail/teamDetail?id=${lawyerId}`
    });
  },

  /**
   * 拨打电话
   */
  callLawyer(e) {
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
      fail: (err) => {
        console.error('拨打电话失败:', err);
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadFavoriteList(true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadFavoriteList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的收藏律师',
      path: '/pages/my/favorite/favorite'
    };
  }
}); 